<template>
  <div ref="div" class="wrap" contenteditable="true">
    <!-- <span class="text"></span>
    <div class="tag" :contenteditable="false">我是标签</div>
    <span class="text"></span>
    <div class="tag" :contenteditable="false">我是标签</div>
    <span>sadasds</span> -->
    <component :is="customCom"></component>
  </div>
</template>

<script setup>
import { ref, h, onMounted } from 'vue';

const div = ref();
const customCom = ref();

const list = [
  {
    type: 'text',
    content: '我是文本',
  },
  {
    type: 'tag',
    content: '我是标签',
  },
  {
    type: 'text',
    content: '我是文本',
  },
];

const getCom = () => {
  return () =>
    list.map(item => {
      if (item.type === 'text') {
        return h('span', { class: 'text' }, item.content);
      } else if (item.type === 'tag') {
        return h('div', { class: 'tag', contenteditable: false }, item.content);
      }
    });
};

const getRange = () => {
  const selection = window.getSelection();
  const range = selection.rangeCount > 0 ? selection.getRangeAt(0) : null;

  if (range) {
    const preCaretRange = range.cloneRange();
    preCaretRange.selectNodeContents(div.value);
    preCaretRange.setEnd(range.startContainer, range.startOffset);
    const cursorPosition = preCaretRange.toString().length;
    console.log('光标位置:', cursorPosition);
  }
};

onMounted(() => {
  customCom.value = getCom();
  div.value.addEventListener('keyup', getRange);
  div.value.addEventListener('mouseup', getRange);
});
</script>

<style scoped lang="scss">
.wrap {
  display: flex;
  :deep() {
    .text {
      padding: 0 1px;
    }
    .tag {
      color: blue;
    }
  }
}
</style>
